package com.example.homeworkdev.Dao;

import static android.content.ContentValues.TAG;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.homeworkdev.util.DatabaseHelper;

public class UserDao {
    private final DatabaseHelper dbHelper;

    public UserDao(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    // 用户注册
    public boolean registerUser(String phone, String password) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_PHONE, phone);
        values.put(DatabaseHelper.COLUMN_PASSWORD, password); // 实际应加密存储);

        long result = db.insert(DatabaseHelper.TABLE_NAME, null, values);
        db.close();
        return result != -1; // 返回 true 表示注册成功
    }

    // 用户登录
    public boolean loginUser(String phone, String password) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] columns = {DatabaseHelper.COLUMN_ID};
        String selection = DatabaseHelper.COLUMN_PHONE + " = ? AND " +
                DatabaseHelper.COLUMN_PASSWORD + " = ?";
        String[] selectionArgs = {phone, password};

        Cursor cursor = db.query(
                DatabaseHelper.TABLE_NAME,
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        boolean exists = cursor.moveToFirst();
        cursor.close();
        db.close();
        return exists; // 返回 true 表示登录成功
    }

    // 检查手机号是否已被注册
    public boolean checkPhoneExists(String phone) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] columns = {DatabaseHelper.COLUMN_PHONE};
        String selection = DatabaseHelper.COLUMN_PHONE + " = ?";
        String[] selectionArgs = {phone};

        Cursor cursor = db.query(
                DatabaseHelper.TABLE_NAME,
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        boolean exists = cursor.getCount()>0;
        cursor.close();
        db.close();
        return exists;
    }

    //删除指定数据(目前想法是在用户登录后，自己点击注销按钮实现删除操作)
    public int deleteUserByPhone(String phone) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String selection = DatabaseHelper.COLUMN_PHONE + " = ?";
        String[] selectionArgs = { phone };

        return db.delete(DatabaseHelper.TABLE_NAME, selection, selectionArgs);
    }

}
